package com.lc.controller;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lc.controller.utils.R;
import com.lc.domain.Book;
import com.lc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController
{
	@Autowired
	private BookService bookService;
	
	
	//	"添加成功^_^"    "添加失败-_-!"
	
	@Value("成功^_^")
	private String success;
	
	@Value("失败-_-!")
	private String fail;

	
	@GetMapping
	public R getAll()
	{
		return new R(true, bookService.list());
	}
	
	@GetMapping("/{id}")
	public R getById(@PathVariable Integer id)
	{
		return new R(true, bookService.getById(id));
	}
	
	@PostMapping
	public R save(@RequestBody Book book) throws IOException
	{
//		if (book.getName().equals("123")) throw new IOException();
		boolean save = bookService.save(book);
		return new R(save, save ? success : fail);
	}
	
	@PutMapping
	public R update(@RequestBody Book book)
	{
		boolean update = bookService.updateById(book);
		return new R(update, update ? success : fail);
	}
	
	@DeleteMapping("/{id}")
	public R delete(@PathVariable Integer id)
	{
		boolean delete = bookService.removeById(id);
		return new R(delete, delete ? success : fail);
	}
	
	
//	@GetMapping("/{currentPage}/{pageSize}")
//	public R getPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize)
//	{
//		IPage page = bookService.page(new Page(currentPage, pageSize));
//		//如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
//		if (currentPage > page.getPages())
//		{
//			page = bookService.page(new Page(page.getPages(), pageSize));
//		}
//		return new R(page != null, page);
//	}
	
	@GetMapping("/{currentPage}/{pageSize}")
	public R getPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize, Book book)
	{
//		System.out.println(book);
		LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper();
		lqw.like(book.getType() != null, Book::getType, book.getType());
		lqw.like(book.getName() != null, Book::getName, book.getName());
		lqw.like(book.getDescription() != null, Book::getDescription, book.getDescription());
		IPage page = bookService.page(new Page(currentPage, pageSize), lqw);
		//如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
		if (currentPage > page.getPages())
		{
			page = bookService.page(new Page(page.getPages(), pageSize),lqw);
		}
		return new R(page != null, page);
	}
}
